/**
 * 07-08-商品-商品管理 <br/>
 *
 * @author fsl fzh 20151125.
 * @author fsl gonglong 20151126.
 *
 */
$(function () {

    initPage();

    bindEvent();
    
    // 获取所有(两个)tab的数据.
    getGoodsList(1, -1);

});

/**
 * 初始化页面.比如: 状态-下拉列表框.<br/>
 *
 * @author fsl-gonglong-20151126.
 */
function initPage() {

    // 商品属性
    adminUtil.getSelectHtml('#good_property', PAGE_DATA.goods_property || []);

    // 状态
    adminUtil.getSelectHtml('#good_state', PAGE_DATA.state || []);
    // 分类
    adminUtil.getSelectHtml('#classify_0', PAGE_DATA.classify || []);
};

/**
 * 绑定事件.<br/>
 *
 * @author fsl-gonglong-20151126.
 */
function bindEvent() {

    // [所有商品|违规下架] 标签的切换
    var tab_body = "#tab-body-";
    $("#top-tab").on("click", "button", function () {

        var idx = $(this).index();
        $(this).addClass("am-btn-primary").siblings().removeClass("am-btn-primary");
        $(tab_body + idx).show().siblings().hide();

    });

    // 分类
    $("#classify_0").on("change", function () {

        var classifyVal = $(this).val();

        if (!!classifyVal) {
            getClassify(classifyVal);
            $("#classify_1").show();
        } else {
            $("#classify_1").hide();
        }

    });

    // 搜索.
    $("#search-btn").on("click", function () {
        getGoodsList(1);
    });

    // 批量-恢复上架,
    $("#remove-on-multi").on("click", function () {

        var tab_body = $(this).parents(".sel-tab-body");

        var goodsIdAry = [];
        tab_body.find("tbody").find(":checkbox:checked").each(function () {
            goodsIdAry.push($(this).attr("id"));
        });

        if (goodsIdAry.length == 0) {
            var conf = {
                title : "提示",
                message : "请先选择需要[恢复上架]的数据!",
                ok_txt : "确定"
            };

            adminUtil.showMsg(conf);

            return false;
        }

        var tmpUrl = PAGE_DATA.REST_API.remove_on_multi_goods + "?page=" +
            tab_body.find(".admin-paging").attr("current-page") + "&pageSize=10";

        updateStatus(tmpUrl, goodsIdAry);
    });

    // 批量-违规下架
    $("#remove-off-multi").on("click", function () {

        var tab_body = $(this).parents(".sel-tab-body");

        var goodsIdAry = [];
        tab_body.find("tbody").find(":checkbox:checked").each(function () {
            goodsIdAry.push($(this).attr("id"));
        });

        if (goodsIdAry.length == 0) {
            var conf = {
                title : "提示",
                message : "请先选择需要[违规下架]的数据!",
                ok_txt : "确定"
            };

            adminUtil.showMsg(conf);

            return false;
        }

        var tmpUrl = PAGE_DATA.REST_API.remove_off_multi_goods + "?page=" +
            tab_body.find(".admin-paging").attr("current-page") + "&pageSize=10";

        updateStatus(tmpUrl, goodsIdAry);
    });

    // 所有商品--列表操作:违规下架;
    $(tab_body + 0).on("click", ".withdraw-btn", function () {
        var that = this;
        var removeOff = function () {
            var removeOffHref = $(this).attr("href") || '';
            updateStatus(removeOffHref);
        };
        var conf = {
            title : "来自网页的消息",
            message : "确定下架吗?",
            ok_func : removeOff,
            ok_context : that,
            ok_param : null
        };
        adminUtil.showConfDialog(conf);
    });
    
    // 所有商品--列表操作:恢复上架;
    $(tab_body + 0).on("click", ".grounding-btn", function () {
        var that = this;
        var removeOn = function () {
            var removeOnHref = $(this).attr("href") || '';
            updateStatus(removeOnHref);
        };
        var conf = {
            title : "来自网页的消息",
            message : "确定恢复上架吗?",
            ok_func : removeOn,
            ok_context : that,
            ok_param : null
        };
        adminUtil.showConfDialog(conf);
    });

    // 所有商品 -- 全选, 删除;
    bindTabEvent(0);

    // 违规下架 -- 列表操作:恢复上架;
    $(tab_body + 1).on("click", ".grounding-btn", function () {
        var that = this;
        var removeOn = function () {
            var removeOnHref = $(this).attr("href") || '';
            updateStatus(removeOnHref);
        };
        var conf = {
            title : "来自网页的消息",
            message : "确定恢复上架吗?",
            ok_func : removeOn,
            ok_context : that,
            ok_param : null
        };
        adminUtil.showConfDialog(conf);
    });

    // 违规下架 -- 全选, 删除;
    bindTabEvent(1);

};

/**
 * 获取二级分类数据.  .<br/>
 *
 * @param classifyId {String}一级分类ID
 *
 * @author fsl-FZH-20151125.
 */
function getClassify(classifyId) {

    $.ajax({
        url : PAGE_DATA.REST_API.secendCategory,
        type : "post",
        dataType : "json",
        data : {
            code : classifyId,
            _token : COMM_DATA.csrfToken
        },
        success : function (result) {
            var datas = $.extend([], result.data);
            adminUtil.getSelectHtml('#classify_1', datas);
        },
        error : function (result) {

            adminUtil.getSelectHtml('#classify_1', []);

            var errorMsg = "";
            if (typeof result.responseJSON != 'undefined'
                 && typeof result.responseJSON.data != 'undefined') {
                errorMsg = result.responseJSON.data;
            }

            var conf = {
                title : "提示",
                message : errorMsg || "获取数据失败!",
                ok_txt : "确定"
            };

            adminUtil.showMsg(conf);
        }
    });
};

/**
 * 更新商品状态, 上架/下架/删除/批量上架. <br/>
 *
 * @param restApi {string} 数据请求连接.
 * @param goodsId {array} 可选, 商品id.
 *
 */
function updateStatus(restApi, goodsId) {

    var pageVal_0 = $("#comm-paging-0").attr("current-page") || 0;
    var pageVal_1 = $("#comm-paging-1").attr("current-page") || 0;

    $.ajax({
        url : restApi || '',
        type : "put",
        data : {
            page_0 : parseInt(pageVal_0),
            page_1 : parseInt(pageVal_1),
            pageSize : 10,
            ids : goodsId || '',
            _token : COMM_DATA.csrfToken
        },
        success : function (result) {
            // 重新渲染 两个tab 列表
            renderList(result);
        },
        error : function (result) {
            // Object {readyState: 4, responseText: "{"data":"\u5bc6\u7801\u9519\u8bef"}",
            // responseJSON: Object, status: 403, statusText: "Forbidden"}

            var errorMsg = "";
            if (typeof result.responseJSON != 'undefined'
                 && typeof result.responseJSON.data != 'undefined') {
                errorMsg = result.responseJSON.data;
            }

            var conf = {
                title : "提示",
                message : errorMsg || "更新数据失败!",
                ok_txt : "确定"
            };

            adminUtil.showMsg(conf);
        }

    });
};

/**
 * 为 单个 tab 绑定事件 -- 全选, 删除; <br/>
 *
 * @param index {int} 当前tab下标.
 *
 * @author fsl-gonglong-20151126.
 *
 */
function bindTabEvent(index) {

    var tbody = $("#goods-context-" + index);
    var chkAll = $("#sel-all-chk-" + index);
    var delMulti = $("#del-multi-btn-" + index);

    // 每行数据的, 选中效果
    tbody.on("click", ".sel-chk", function () {
        var chkObj = $(this).find(":checkbox");
        var chkVal = chkObj.prop("checked");
        chkObj.prop("checked", !chkVal);

        var unChk = tbody.find(":checkbox:not(:checked)").length;
        chkAll.prop("checked", (unChk == 0));

        return;
    });

    // 默认冒泡事件.
    tbody.on("click", ":checkbox", function (event) {
        // event.stopPropagation();
        var chkVal = $(this).prop("checked");
        $(this).prop("checked", !chkVal);

    });

    // 全选.
    chkAll.on("click", function () {
        var chkAllVal = $(this).prop("checked");
        tbody.find(":checkbox").prop("checked", chkAllVal); ;
    });

    // 删除多条记录.
    delMulti.on("click", function () {

        var tab_body = $(this).parents(".sel-tab-body");

        var goodsIdAry = [];
        tab_body.find("tbody").find(":checkbox:checked").each(function () {
            goodsIdAry.push($(this).attr("id"));
        });

        if (goodsIdAry.length == 0) {
            var conf = {
                title : "提示",
                message : "请先选择需要删除的数据!",
                ok_txt : "确定"
            };

            adminUtil.showMsg(conf);

            return false;
        }

        var delMultiUrl = PAGE_DATA.REST_API.del_multi_goods + "?page=" +
            tab_body.find(".admin-paging").attr("current-page") + "&pageSize=10";

        updateStatus(delMultiUrl, goodsIdAry);
    });
};

/**
 * 获取商品数据列表.<br/>
 *
 * @param page {int} 页码.
 * @param tabVal {int} 可选, 当前tab下标。所有tab: -1.
 *
 */
function getGoodsList(page, tabVal) {

    var onClickObj = {
        onClick : function () {
            var clickPage = $(this).attr("data-page");
            getGoodsList(clickPage);
        }
    };

    var tempTabVal = tabVal || $("#top-tab").find(".am-btn-primary").index();
    var goodNameVal = $("#good_name").val();
    var storeNameVal = $("#store_name").val();
    var brandNameVal = $("#brand_name").val();
    var goodPropVal = $("#good_property").val();
    var stateVal = $("#good_state").val();

    var classifyVal_0 = $("#classify_0").val();
    var classifyVal_1 = $("#classify_1").val();

    $.ajax({
        url : PAGE_DATA.REST_API.get_goods_list,
        type : "get",
        dataType : "json",
        data : {

            tab : tempTabVal, // 所有商品:0, 违规下架:1;
            goodName : goodNameVal,
            storeName : storeNameVal,
            brandName : brandNameVal,
            goodProp : goodPropVal,
            state : stateVal,
            classify_0 : classifyVal_0,
            classify_1 : classifyVal_1,

            page : parseInt(page || 0),
            pageSize : 10,
        },
        success : function (result) {
            if (parseInt(result.tab) < 0) {
                renderList(result);
            } else {
                renderTab(result.tab, result.data[0]);
            }
        },

        error : function (result) {

            var errorMsg = "";
            if (typeof result.responseJSON != 'undefined'
                 && typeof result.responseJSON.data != 'undefined') {
                errorMsg = result.responseJSON.data;
            }

            var conf = {
                title : "提示",
                message : errorMsg || "获取数据失败!",
                ok_txt : "确定"
            };

            adminUtil.showMsg(conf);
        }
    })

};

/**
 * 渲染列表数据, 翻页.
 *
 * @param ajaxResult {object} ajax请求返回的数据对象.
 *
 * @author fsl-gonglong-20151126
 */
function renderList(ajaxResult) {

    for (var i = 0, len = ajaxResult.data.length; i < len; i++) {
        renderTab(i, ajaxResult.data[i]);
    }

};

/**
 * 渲染单个列表 和 翻页.<br/>
 *
 * @param idx {int} 当前tab下标.
 * @param tabData {object} 列表和翻页控件 数据.
 *
 * @author fsl-gonglong-20151126.
 */
function renderTab(idx, tabData) {

    var tbbody = "#goods-context-";
    var paging = "#comm-paging-";

    // 商品列表模板
    var goodTempl = _.template($("#goods-list-templ").html());
    var goodsHtml = goodTempl(tabData.detail);
    $(tbbody + idx).html(goodsHtml);

    var defaultPagingObj = {
        total : 0,
        pageSize : 0,
        page : 0
    };

    var onClickObj = {
        onClick : function () {
            var clickPage = $(this).attr("data-page");
            getGoodsList(clickPage);
        }
    };

    var pagingConf = $.extend(defaultPagingObj, tabData.pagingConfData, onClickObj);
    adminUtil.initPaging('#comm-paging-' + idx, pagingConf);

};